package com.wltjack.sysmanage.modules.demo1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wltjack.sysmanage.common.DataSourceSwitch;
import com.wltjack.sysmanage.common.enums.DataSourceTypeEnum;
import com.wltjack.sysmanage.common.util.TableFieldUtil;
import com.wltjack.sysmanage.modules.demo1.dto.DeptListDto;
import com.wltjack.sysmanage.modules.demo1.dto.DeptAddDto;
import com.wltjack.sysmanage.modules.demo1.dto.DeptPageDto;
import com.wltjack.sysmanage.modules.demo1.entity.Dept;
import com.wltjack.sysmanage.modules.demo1.mapper.DeptMapper;
import com.wltjack.sysmanage.modules.demo1.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName DeptServiceImpl
 * @Description DeptService实现类
 * @Author kangliang
 * @Date 2021/03/01 13:50
 * @Version 1.0
 */
@Slf4j
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @DataSourceSwitch(DataSourceTypeEnum.DB2)
    @Override
    public Map<String, Object> list(DeptListDto dto) {
        List<Dept> deptList = deptMapper.selectList(Wrappers.<Dept>lambdaQuery().orderByAsc(Dept::getId));
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("mysql data", deptList);
        return resultMap;
    }

    @DataSourceSwitch(DataSourceTypeEnum.DB2)
    @Override
    public boolean insert(DeptAddDto dto) {
        Dept dept = new Dept();
        dept.setName(dto.getName());
        deptMapper.insert(dept);
        return true;
    }

    @DataSourceSwitch(DataSourceTypeEnum.DB2)
    @Override
    public Page<Dept> queryDeptPage(DeptPageDto dto) {
        Page<Dept> page = new Page(dto.getPageNumber(), dto.getPageSize());

        QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
        // 字段排序
        if (StringUtils.isNotBlank(dto.getSort())) {
            String tableFieldValue = TableFieldUtil.getTableFieldValue(Dept.class, dto.getSort());
            queryWrapper.orderBy(Boolean.TRUE, StringUtils.equalsIgnoreCase(dto.getOrder(), "asc") ? true : false, tableFieldValue);
        } else {
            queryWrapper.lambda().orderByDesc(Dept::getId);
        }

        queryWrapper.lambda()
                .like(StringUtils.isNotBlank(dto.getName()), Dept::getName, dto.getName());

        Page<Dept> resultPage = deptMapper.selectPage(page, queryWrapper);
        return resultPage;
    }

}
